#!/usr/bin/python
import os
import subprocess
from email.Utils import formatdate
from optparse import OptionParser

parser = OptionParser(usage="usage: %prog [options]")
parser.set_defaults(
    BASE_VERSION='1.0',
    PACKAGE_NAME='unknownpackage'
)

parser.add_option('-p', '--packagename', type='string', help='debian package name', dest='PACKAGE_NAME')
parser.add_option('-b', '--base-version', type='string', help='base version number', dest='BASE_VERSION')

options = parser.parse_args()[0]

ROOT_DIR  = os.path.realpath(os.path.dirname(__file__))

def get_versions():
    """
    Returns last build version from LAST_VERSION file and current svn revision
    """
    last_build_version = get_last_version()
    current_version = get_svn_revision()
    return last_build_version, current_version

def get_last_version():
    """
    Returns last build version from LAST_VERSION file
    """
    last_version_file = os.path.join(ROOT_DIR, 'debian', 'LAST_VERSION')

    data = ''
    if os.path.exists(last_version_file):
        data = open(last_version_file, 'r').read()
    return data and int(data) or 0

def get_svn_revision():
    """
    Calls 'svn up' and parses revision from output
    """
    svn_out = subprocess.Popen(['svn', 'info'], env=dict(os.environ, LC_ALL='EN'), stdout=subprocess.PIPE).communicate()[0]

    if not svn_out:
        raise Exception('Cannot get revision info from svn')

    try:
        svn_params = dict(line.strip().split(': ', 1)
            for line in svn_out.split('\n') if ': ' in line)
        return int(svn_params['Revision'])
    except:
        raise Exception, 'Cannot parse revision from `%s`' % svn_out

def get_changelog_from_svn(rev_from, rev_to):
    """
    Returns *-formatted changelog from subversion
    """

    cmd= ''
    if rev_to - rev_from > 1:
        cmd = 'svn log -r %d:%d' % (rev_from, rev_to)
    else:
        cmd = 'svn log -r %d' % rev_to
    svn_out = subprocess.Popen(cmd.split(), env=dict(os.environ, LC_ALL='EN'), stdout=subprocess.PIPE).communicate()[0]
    lines = [s.strip(' -') for s in svn_out.split('\n')]
    return '\n'.join('  * %s' % line for line in lines
        if not line == '' and
        not line.startswith('-----') and
        not (line[0] == 'r' and (line.endswith(' lines') or line.endswith(' line'))))

def save_changelog(changelog, cur_version):

    changelog_template ="""%(packagename)s (%(base_version)s.%(cur_version)d) unstable; urgency=low

%(changelog)s

 -- maxim oransky <maxim.oransky@gmail.com>  %(timestamp)s
"""

    sub = {
        'packagename': options.PACKAGE_NAME,
        'base_version': options.BASE_VERSION,
        'changelog': changelog,
        'cur_version': cur_version,
        'timestamp': formatdate(localtime=True)
    }

    old_changelog = read_changelog()

    changelog_file = os.path.join(ROOT_DIR, 'debian', 'changelog')

    f = open(changelog_file, 'w')
    f.write("\n".join([changelog_template % sub, old_changelog]))
    f.close()

def read_changelog():
    changelog_file = os.path.join(ROOT_DIR, 'debian', 'changelog')

    if os.path.exists(changelog_file):
        return open(changelog_file, 'r').read()
    else:
        return ''

def save_last_version(version):
    """
    Save version value to LAST_VERSION file
    """
    last_version_file = os.path.join(ROOT_DIR, 'debian', 'LAST_VERSION')
    f = open(last_version_file, 'w')
    f.write(str(version))
    f.close()

if __name__ == "__main__":
    last_version, cur_version = get_versions()
    if last_version is not cur_version:
        save_changelog(get_changelog_from_svn(last_version, cur_version), cur_version)
        save_last_version(cur_version)
